<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="实验名称" prop="testName">
            <el-input v-model="queryParams.testName" placeholder="请输入实验名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学科" prop="subject">
            <!-- <el-input v-model="queryParams.subject" placeholder="请输入学科" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.subject" clearable placeholder="请选择学科">
              <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年级" prop="grade">
            <!-- <el-input v-model="queryParams.grade" placeholder="请输入年级" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.grade" clearable placeholder="请选择年级">
                <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
          </el-form-item>
       
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:test:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <h2>实验目录列表</h2>
      </template>

      <el-table v-loading="loading" :data="testList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="实验编号" align="center" prop="id" v-if="true" />
        <el-table-column label="实验名称" align="center" prop="testName" />
        <el-table-column label="学科" align="center" prop="subject" >
          <template #default="scope">
            {{ getSubjectNameById(subjectOptions, scope.row.subject) }}
          </template>
        </el-table-column>
        <el-table-column label="年级" align="center" prop="grade" >
          <template #default="scope">
            <dict-tag :options="sys_grade" :value="scope.row.grade" />
          </template>
          </el-table-column>
      
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button type="text" size="small"  @click="handleUpdate(scope.row)" v-hasPermi="['core:test:edit']">编辑</el-button>
              <el-button type="text" size="small"  @click="handleView(scope.row)" v-hasPermi="['core:test:edit']">查看</el-button>
              <el-button type="text" size="small"  @click="handleDelete(scope.row)" v-hasPermi="['core:test:remove']">删除</el-button>
          
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
  
  </div>
</template>

<script setup name="Test" lang="ts">
import { listTest, getTest, delTest, addTest, updateTest } from '@/api/core/test';
// import { StepDetail,TestVO, TestQuery, TestForm } from '@/api/core/test/types';
import {  TestVO, TestQuery, TestForm } from '@/api/core/test/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// const stepList = ref<StepDetail[]>([]);

import { getSubjectNameById } from '@/utils/index';
// 学校
import { useSchoolList } from '@/composables/useSchoolList';
const { deptOptions, fetchSchoolList } = useSchoolList();
//学科
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();
const { sys_notice_type, sys_period, sys_grade } = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_period', 'sys_grade'));


const testList = ref<TestVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const testFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 定义 StepDetail 接口
// interface StepDetail {
//   conentId: string | number;
//   stage: string;
//   stepName: string;
//   detail: string;
// }
const initFormData: TestForm = {
  id: undefined,
  testName: undefined,
  subject: undefined,
  grade: undefined,
  principle: undefined,
  stepList: []
}
const data = reactive<PageData<TestForm, TestQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    testName: undefined,
    subject: undefined,
    grade: undefined,
    principle: undefined,
    stepList: [],
    params: {
    }
  },
  rules: {
    testName: [
      { required: true, message: "实验名称不能为空", trigger: "blur" }
    ],
    subject: [
      { required: true, message: "学科不能为空", trigger: "blur" }
    ],
    grade: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    principle: [
      { required: true, message: "实验原理不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询实验目录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTest(queryParams.value);
  testList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  testFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: TestVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  // reset();
  // dialog.visible = true;
  // dialog.title = "添加实验目录";
  router.push({ path: '/experiment/test/testStep/',query: { type:0}});
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TestVO) => {

  const id = row?.id || ids.value[0]
  router.push({ path: '/experiment/test/testStep/',query: { id: id,type:1}});
}
/** 查看按钮 */
const handleView = async (row?: TestVO) => {
  const id = row?.id || ids.value[0]
  router.push({ path: '/experiment/test/testStep/',query: { id: id,type:2}});
}

/** 提交按钮 */
const submitForm = () => {
  testFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTest(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addTest(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: TestVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除实验目录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delTest(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('core/test/export', {
    ...queryParams.value
  }, `test_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  fetchSubjectList()
});
</script>
